import queue
import logging
import threading
import time
import cv2


class Record:
    def __init__(self):
        self.run = False
        self.__log_init()

    def __log_init(self):
        self.logger = logging.getLogger("Record")

    def open(self, fps, width, height, filename=None):
        self.logger.trace("open.enter")
        if filename is None:
            filename = f'logs/{time.strftime("%Y%m%d-%H%M", time.localtime())}.mp4'
        fourcc = cv2.VideoWriter_fourcc(*"mp4v")
        self.writer = cv2.VideoWriter(filename, fourcc, fps, (width, height))
        self.logger.trace("open.done")
        return True

    def close(self):
        self.logger.trace("close.enter")
        self.run = False
        if self.writer:
            self.writer.release()
            self.logger.info("release video writer")
        self.logger.trace("close.done")

    def thread(self):
        self.logger.trace("thread.enter")

        while self.run:
            try:
                data = self.inqueue1.get(timeout=0.5)
            except queue.Empty as e:
                # self.logger.spam("input queue get timeout!")
                continue
            except Exception as e:
                self.logger.error("input queue error!")
                continue

            frame, number = data
            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            self.writer.write(frame)

            # self.logger.spam("thread running...")

        self.logger.trace("thread.done")

    def start(self):
        self.logger.trace("start.enter")
        self.run = True
        self.handle = threading.Thread(target=self.thread)
        self.handle.start()
        self.logger.trace("start.done")
        return True

    def stop(self):
        self.logger.trace("stop.enter")
        self.run = False
        self.handle.join()
        self.logger.trace("stop.done")

    def input_queue_set(self, input_queue_list):

        self.logger.trace('input_queue_set.enter')

        if self.run:
            self.logger.error("this is opened, please close the this first!")
            return False
        
        if not isinstance(input_queue_list, list):
            input_queue_list = [input_queue_list]

        for input_queue in input_queue_list:
            if not isinstance(input_queue, queue.Queue):
                self.logger.error("one queue is not a queue!")
                return False

        # 针对项目需求，设置服务输入的队列
        self.inqueue1 = input_queue_list[0] 

        self.logger.trace('input_queue_set.done')
        return True
